package com.qyxx.platform.sysmng.attach.service;

import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.gsc.exception.GscException;
import com.qyxx.platform.gsc.utils.Constants;
import com.qyxx.platform.gsc.utils.SystemParam;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.attach.dao.AttachDao;
import com.qyxx.platform.sysmng.attach.dao.AttachListDao;
import com.qyxx.platform.sysmng.attach.entity.Attach;
import com.qyxx.platform.sysmng.attach.entity.AttachList;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 *  附件管理类
 */
@Component
@Transactional
public class AttachManager {
	
	private AttachDao attachDao;
	private AttachListDao attachlistDao;
	private UserDao userDao;
	
	@Autowired
	public void setAttachDao(AttachDao attachDao) {
		this.attachDao = attachDao;
	}
	@Autowired
	public void setAttachlistDao(AttachListDao attachlistDao) {
		this.attachlistDao = attachlistDao;
	}

	/**
	 * @param userDao
	 */
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	/**
	 * 上传附件文件处理
	 * 先向数据库插入数据，然后再上传文件，这样如果数据库数据插入失败，可以进行事物回滚机制
	 */
	public String saveFile(Long id,File filedata,String filename,SystemParam sp,Long userId) {
		String fileForderName = DateFormatUtils.format(new Date(), "yyyyMMdd");//获取系统时间，形式20120730
		Long fileSize = filedata.length();//文件大小
		String filePackage = sp.getUploadPicPath()
				+ Constants.UPLOADFILE_PATH;//文件路径E:/upload/gs-attach/
		String filePath=Constants.UPLOADFILE_ATTACH
				+ fileForderName +Constants.PATH_SEPARATOR +/*DateFormatUtils.format(System.currentTimeMillis(),"yyyyMMddHHmmssSSS")*/
				UUID.randomUUID().toString().replace("-", "") //全局唯一性
				+ filename.substring(filename.lastIndexOf("."),
				filename.length());//   attach/20120703/20120703092757781.xxx
		File destFile = new File(filePackage + filePath);//具体的文件位置
		Date nowDate = new Date();
		// 订单列表中的acctachID来判断
		AttachList attachList = new AttachList();
		if(id==null){
			Attach entity = new Attach();
			entity.setCreateUser(userId);
			entity.setCreateTime(nowDate);
			attachDao.save(entity);
			id = entity.getId();	
			attachList.setAttachId(id);
			attachList.setFilePath(filePath);
			attachList.setFileSize(fileSize);
			attachList.setFileName(filename);
			attachList.setCreateTime(nowDate);
			attachList.setCreateUser(userId);
			attachlistDao.save(attachList);
		}else{
			//先做判断，检查attachId是否存在，如果不存在，则生成新的ID
			List<Attach> attList = attachDao.findBy("id", id);
			if(attList == null || attList.isEmpty()) {
				Attach entity = new Attach();
				entity.setCreateUser(userId);
				entity.setCreateTime(nowDate);
				attachDao.save(entity);
				id = entity.getId();
			}
			attachList.setAttachId(id);
			attachList.setFilePath(filePath);
			attachList.setFileSize(fileSize);
			attachList.setFileName(filename);
			attachList.setCreateTime(nowDate);
			attachList.setCreateUser(userId);
			attachlistDao.save(attachList);
		}
		try {	
			FileUtils.copyFile(filedata, destFile);//复制文件		
		} catch (IOException e1) {		
			throw new GscException(filedata.getName() + "文件上传出现异常", e1);
		}
		return String.valueOf(id);
	}
	
	/**
	 * 查询附件列表
	 */
	@Transactional(readOnly = true)
    public  Page<AttachList> findAttachList(Page<AttachList> page, List<PropertyFilter> filters){
		return preHandlePage(attachlistDao.findPage(page, filters));
    }
	
	/**
	 * 删除附件
	 */
	public boolean deleteAttachs(Long[] ids) {
		Long attachId =0L;
		for (Long id : ids) {
		AttachList attachlist =	attachlistDao.get(id);
		attachId = attachlist.getAttachId();
		attachlistDao.delete(id);
		}
		List<AttachList> list  = attachlistDao.findBy("attachId", attachId);
		if(list == null || list.size()<=0){
			attachDao.delete(attachId);			
			return false;
		}
		return true;
	}

	/**
	 * 保存附件总记录
	 * 
	 * @param userId
	 * @return
	 */
	public String saveAttach(Long userId) {
		Attach entity = new Attach();
		entity.setCreateUser(userId);
		entity.setCreateTime(new Date());
		attachDao.save(entity);
		return String.valueOf(entity.getId());
	}
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<AttachList> preHandlePage(Page<AttachList> page) {
		List<AttachList> list = page.getResult();
		if(list != null) {
			for(AttachList n : list) {
				n.setCreateUserCaption(userDao.getUserNameById(n.getCreateUser()));
			}
		}
		return page;
	}

}
